// ==UserScript==
// @name        🌱通威新闻自动化脚本
// @namespace   Violentmonkey Scripts
// @match       *://fmi.tongwei.com:8016/mobileportal/*/home/newsList*
// @icon         https://21tb-file5.21tb.com/sf-server/file/getFile/faea6060ff41010e29235a87b176ff3e-N_1523333333333/60af80f6a3102fedcd26bc80_0100
// @require      https://code.jquery.com/jquery-2.1.4.min.js
// @grant       none
// @version     1.0
// @author      -
// @license      MIT
// @description 2025/1/24 16:38:41
// ==/UserScript==

// 同步任务数量
var threadCount = 2;
// 单个新闻阅读时间
var readTime = 10;

// 创建一个控制台
function createConsole() {
    const progressDiv = document.createElement('div');
    progressDiv.style.class = 'bing_auto';
    progressDiv.style.position = 'fixed';
    progressDiv.style.bottom = '0';
    progressDiv.style.left = '0';
    progressDiv.style.width = '100%';
    progressDiv.style.backgroundColor = '#555';
    progressDiv.style.zIndex = '10001'; // 确保在iframe和关闭按钮之上
    progressDiv.style.textAlign = 'center';
    progressDiv.style.height = '50px'; // 添加固定高度
    progressDiv.style.display = 'flex'; // 使用flex布局
    progressDiv.style.justifyContent = 'center'; // 水平居中
    progressDiv.style.alignItems = 'center'; // 垂直居中
    document.body.appendChild(progressDiv);
    return progressDiv;
}

// 创建一个控制台按钮
function createButton(text, onClick) {
    const button = document.createElement('button');
    button.innerHTML = text;
    button.style.marginRight = '10px';
    button.style.padding = '10px'; // 添加顶部外边距
    button.style.display = 'none';
    button.addEventListener('click', onClick);
    return button;
}

// 创建一个控制台日志框
function createLogDiv() {
    const logdiv = document.createElement('div');
    logdiv.style.color = 'white';
    logdiv.style.padding = '20px';
    logdiv.style.textAlign = 'center';
    logdiv.style.justifyContent = 'center'; // 水平居中
    logdiv.style.alignItems = 'center'; // 垂直居中
    logdiv.innerHTML = '点击启动';
    return logdiv;
}

/**
 * 创建一个iframe容器
 * @returns 容器
 */
function createContainerDiv() {
    let containerDiv = document.createElement('div');
    containerDiv.className = 'container-flex';
    Object.assign(containerDiv.style, {
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: 9999,
        backgroundColor: 'white',
        display: 'flex',
        flexWrap: 'wrap'
    });
    document.body.appendChild(containerDiv);
    return containerDiv;
}
/**
 * 创建一个阅读器iframe
 * @param {*} positionNum
 * @param {*} windowSize
 * @param {*} url
 * @returns
 */
function createReaderIframe(positionNum, windowSize, url) {
    let readerIframe = document.createElement('iframe');
    readerIframe.className = `bingIframe-${positionNum}`;
    readerIframe.src = url;
    readerIframe.width = windowSize + '%';
    readerIframe.height = '100%';
    readerIframe.style.border = 'none';
    readerIframe.style.top = '0';
    readerIframe.style.left = (positionNum - 1) * windowSize + '%';
    readerIframe.style.zIndex = '9999';
    readerIframe.style.backgroundColor = 'white';
    return readerIframe;
}
/**
 * 创建一个阅读器的日志框
 * @returns
 */
function createReaderLog() {
    let readerLog = document.createElement('div');
    readerLog.style.class = 'bing_iframe_log';
    readerLog.style.position = 'fixed';
    readerLog.style.bottom = '50px';
    readerLog.style.left = '0';
    readerLog.style.width = '100%';
    readerLog.style.backgroundColor = '#333';
    readerLog.style.zIndex = '10000';
    readerLog.style.textAlign = 'center';
    readerLog.style.height = '50px';
    readerLog.style.display = 'flex';
    readerLog.style.justifyContent = 'center';
    readerLog.style.alignItems = 'center';
    return readerLog;
}
/**
 * 创建一个阅读器的关闭按钮
 * @returns
 */
function createCloseButton() {
    // 创建一个关闭按钮元素
    let closeButton = document.createElement('button');
    closeButton.innerHTML = '关闭';
    closeButton.style.position = 'absolute';
    closeButton.style.top = '10px';
    closeButton.style.right = '10px';
    closeButton.style.zIndex = '10000';
    return closeButton;
}
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 获取30天内未阅读新闻的条数
 * @returns 用户信息
 */
async function getNoReadNum(){
    // 获取当前日期
    const now = new Date();
    // 设置 endDate 为当前日期的 23:59:59
    const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    // 设置 startDate 为 30 天前的 00:00:00
    const startDate = new Date(now);
    startDate.setDate(startDate.getDate() - 30);
    startDate.setHours(0, 0, 0, 0);

    // 格式化日期为 YYYY-MM-DD HH:mm:ss 格式
    const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const formattedStartDate = formatDate(startDate);
    const formattedEndDate = formatDate(endDate);

    var settings = {
        "url": "https://fmi.tongwei.com:8016/fbc-news/news/not/ItwRead?username=",
        "method": "POST",
        "timeout": 0,
        "headers": {
            "pragma": "no-cache",
            "priority": "u=1, i",
            "token": "null",
            "content-type": "application/json;charset=UTF-8"
        },
        // 使用动态生成的日期
        "data": `{"attr":{"empuID":"","isRead":"0","startDate":"${formattedStartDate}","endDate":"${formattedEndDate}"}}`,
    };

    try {
        const response = await $.ajax(settings);
        return response;
    } catch (error) {
        console.error("请求失败", error);
        return null;
    }
}


async function getNewLists(pageSize, pageNum) {
    var settings = {
        "url": "https://fmi.tongwei.com:8016/fbc-news/news/ItwFindTwNews",
        "method": "POST",
        "timeout": 0,
        "headers": {
            "token": "null",
            "content-type": "application/json;charset=UTF-8"
        },
      "data": "{\"attr\":{\"type\":\"mobile\",\"isRead\":\"0\",\"username\":\"\",\"empuID\":\"\"},\"filters\":[{\"key\":\"title\",\"opt\":\"LIKE\",\"type\":\"S\",\"value\":\"\"}],\"pageNum\":" + pageNum + ",\"orderby\":\"\",\"pageSize\":" + pageSize + "}",

    };

    try {
        const response = await $.ajax(settings);
        return response;
    } catch (error) {
        console.error("请求失败", error);
        return null;
    }
}
/**
 * 获取用户信息
 * @returns 用户信息
 */
async function getUserInfo() {
    var settings = {
        "url": "https://fmi.tongwei.com:8016/fbc-personal-center/personal/basic/getEmployeeInfo",
        "method": "GET",
        "timeout": 0,
        "headers": {
            "token": "null",
        },
    };

    try {
        const response = await $.ajax(settings);
        return response;
    } catch (error) {
        console.error("请求失败", error);
        return null;
    }
}

async function loginAndCheck() {
    var cookie_session = prompt("账户未正确登录！\n请输入您的识别码(SESSION):");
    if (!cookie_session) {
        alert("未输入到识别码！\n如需重新登录，请刷新页面！");
        return;
    }

    document.cookie = "SESSION=" + cookie_session + "; path=/;";
    var userInfo = await getUserInfo();

    if (!(userInfo && userInfo["data"] && userInfo["data"]["posName"])) {
        alert("无效识别码！\n如需重新登录，请刷新页面！");
        return;
    }
    alert("登录成功！\n" + userInfo.data.posName + "-" + userInfo.data.displayname);
    location.reload();
}



/**
 * 创建一个新的阅读器
 */
function createReader(positionNum, windowSize, time, url) {
    // 检查iframe阅读器是否存在
    let readerIframe = document.querySelector(`.bingIframe-${positionNum}`);
    if (readerIframe) {
        document.body.removeChild(readerIframe);
    }

    //检查阅读器容器是否存在
    let containerDiv = document.querySelector(".container-flex");
    if (!containerDiv) {
        // 创建阅读器的容器
        containerDiv = createContainerDiv();
    }

    // 创建一个新的iframe阅读器及内组件
    readerIframe = createReaderIframe(positionNum, windowSize, url);
    let closeButton = createCloseButton();
    let readerLog = createReaderLog();

    // 点击按钮移除阅读器iframe
    closeButton.addEventListener('click', function () {
        document.body.removeChild(readerIframe);
    });

    // load事件监听器 - 只有加载完成，才能进行操作，否则报错
    readerIframe.addEventListener('load', function () {
        readerIframe.contentDocument.body.appendChild(readerLog);
        readerIframe.contentDocument.body.appendChild(closeButton);

        //阅读倒计时
        readerLog.innerHTML = `<span style="color: white;">加载中...</span>`;
        let remainingTime = time;//剩余时间
        const timer = setInterval(() => {
            readerLog.innerHTML = `<span style="color: white;">正在阅读，剩余${remainingTime}秒</span>`;
            remainingTime--;
            if (remainingTime < 0) {
                clearInterval(timer);
                readerLog.innerHTML = '<span style="color: white;">阅读完成</span>';
                // 关闭阅读器
                containerDiv.removeChild(readerIframe);
                // 如果阅读器全部被关闭，则移除容器
                if (containerDiv.querySelectorAll('[class^="bingIframe-"]').length == 0) {
                    document.body.removeChild(containerDiv);
                }
            }
        }, 1000);
    });
    containerDiv.appendChild(readerIframe);
    return;
}



/**
 * 获取新闻列表
 */
async function readNews() {
    //只验证是否登录
    var noReadNum = await getNoReadNum();
    //用户无效、重新登录
    if (!(noReadNum && noReadNum["data"])) {
        loginAndCheck();
        return;
    }

    // 是否停止
    let isStopped = false;

    const progressDiv = createConsole();
    const startButton = createButton('开始', startLoop);
    const stopButton = createButton('停止', stopLoop);
    const logdiv = createLogDiv();

    progressDiv.appendChild(logdiv);
    progressDiv.appendChild(startButton);
    progressDiv.appendChild(stopButton);

    function startLoop() {
        isStopped = false;
        startButton.style.display = 'none';
        stopButton.style.display = 'inline';
        loop();
    }


    function stopLoop(log) {
        if (!log)
            log = "请点击开始";
        else if (log['type'])
            log = "手动停止";
        else
            log = log;
        isStopped = true;
        startButton.style.display = 'inline';
        stopButton.style.display = 'none';
        logdiv.innerHTML = log;
    }

    const loop = async () => {

        var noReadNum = await getNoReadNum();
        //用户无效、重新登录
        if (!(noReadNum && noReadNum["data"])) {
            loginAndCheck();
            return;
        }
        // 获取未读数量
        var noReadNum = noReadNum["data"];
        // 转换为integer
        noReadNum = parseInt(noReadNum);
        if (isNaN(noReadNum)) {
            loginAndCheck();
            return;
        }
        if (noReadNum <= 0) {
            stopLoop("完成，你已经没有新闻可以阅读了！");
            return;
        }
        if (noReadNum > 100) {
            noReadNum =100;
        }
        var newLists = await getNewLists(noReadNum, 1);
        //用户无效、重新登录
        if (!(newLists && newLists["data"] && newLists["data"]["list"])) {
            loginAndCheck();
            return;
        }


        // 创建任务池
        const taskPool = newLists["data"]["list"].slice(); // 创建一个副本，避免修改原始数据
        // 重置计数器
        let count = 0;
        // 重置总任务数
        var total = newLists["data"]["list"].length;
        // 是否停止
        isStopped = false;

        while (true) {
            // 检查是否停止
            if (isStopped) break;

            // 检查任务
            for (let positionNum = 1; positionNum <= threadCount; positionNum++) {

                // 检查任务是否结束
                if (document.querySelector(`.bingIframe-${positionNum}`))
                    continue;

                //发放任务
                // 从堆栈顶部取出任务
                const task = taskPool.shift();
                //获取新闻页
                readUrl = 'https://fmi.tongwei.com:8016/mobileportal/#/home/newsDetail?id=' + task["id"];
                //创建任务视窗
                createReader(positionNum, 100 / threadCount, readTime, readUrl);
                count++;
                logdiv.innerHTML = `进度: ${count}/${total}`;
                await delay(2000); // 等待2秒

                if (count >= total) {
                    await delay(5000); // 等待2秒
                    stopLoop("任务发放完成！");
                    return;
                }
            }
            await delay(1000); // 等待1秒
        }
    };
    stopLoop();
}


readNews();
function PreventHibernation(){
  const chromeVersion = /Chrome\/([0-9.]+)/
    .exec(window?.navigator?.userAgent)?.[1]
    ?.split('.')[0];

  if (chromeVersion && parseInt(chromeVersion, 10) >= 88) {
    const videoDom = document.createElement('video');
    const hiddenCanvas = document.createElement('canvas');

    videoDom.setAttribute('style', 'display:none');
    videoDom.setAttribute('muted', '');
    videoDom.muted = true;
    videoDom.setAttribute('autoplay', '');
    videoDom.autoplay = true;
    videoDom.setAttribute('playsinline', '');
    hiddenCanvas.setAttribute('style', 'display:none');
    hiddenCanvas.setAttribute('width', '1');
    hiddenCanvas.setAttribute('height', '1');
    hiddenCanvas.getContext('2d')?.fillRect(0, 0, 1, 1);
    videoDom.srcObject = hiddenCanvas?.captureStream();
}
}
PreventHibernation();

